#!/bin/bash
{
	#////////////////////////////////////
	# DietPi PostBoot Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /boot/dietpi/postboot
	# - DietPi-Update check and DietPi-Services start on regular boot
	# - Executes optional user scripts from: /var/lib/dietpi/postboot.d/
	# - Prints login banner
	#////////////////////////////////////

	EXIT_CODE=0
	G_DIETPI_INSTALL_STAGE=$(</boot/dietpi/.install_stage)

	# Regular boot
	if [[ $G_DIETPI_INSTALL_STAGE == 2 ]]; then

		# Check for DietPi updates if chosen
		grep -q '^[[:blank:]]*CONFIG_CHECK_DIETPI_UPDATES=1' /boot/dietpi.txt && /boot/dietpi/dietpi-update 2 &> /dev/null &

		# Start DietPi controlled services
		/boot/dietpi/dietpi-services start || EXIT_CODE=$?

	fi

	# Execute optional user scripts
	for f in /var/lib/dietpi/postboot.d/*
	do

		[[ $f != *'/readme.txt' && -f $f ]] || continue
		[[ -x $f ]] || chmod +x "$f"
		echo -e "\e[90m[\e[0m INFO \e[90m] DietPi-PostBoot | Running user script: ${f##*/}\e[0m"
		"$f" || { EXIT_CODE=$?; echo -e "\e[90m[\e[31mFAILED\e[90m] DietPi-PostBoot |\e[0m User script ${f##*/} failed with exit code: $EXIT_CODE"; }

	done

	# Print DietPi login banner if no autologin selected
	if [[ ! -f '/etc/systemd/system/getty@tty1.service.d/dietpi-autologin.conf' ]]; then

		echo
		/boot/dietpi/func/dietpi-banner 0
		# Print default login credentials only on first boot
		[[ $G_DIETPI_INSTALL_STAGE == 2 ]] || echo -e '\n Default Login:\n Username = root\n Password = dietpi (or custom dietpi.txt entry)'
		echo -e '\n Please hit <return> to login\n'

	fi

	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
